﻿#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.Admin.Core.Middlewares/RecordAccessLogsMilddware 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       N/A
* 类 名：       RecordAccessLogsMilddware
* 创建时间：  2025/5/23 18:54:16
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using SSPivot.AspNetCore.Abstractions.User;
using SSPivot.Common;
using SSPivot.Common.Helpers;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace SSPivot.Admin.Core.Middlewares
{
    /// <summary>
    /// 记录用户方访问数据
    /// </summary>
    public class RecordAccessLogsMilddware
    {
        /// <summary>
        ///
        /// </summary>
        private readonly RequestDelegate _next;
        private readonly ICurrentUser _user;

        private readonly ILogger<RecordAccessLogsMilddware> _logger;
        private readonly Stopwatch _stopwatch;
        private IConfiguration _configuration;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="next"></param>
        /// <param name="user"></param>
        /// <param name="logger"></param>
        public RecordAccessLogsMilddware(RequestDelegate next, ICurrentUser user, ILogger<RecordAccessLogsMilddware> logger, IConfiguration configuration)
        {
            _next = next;
            _user = user;
            _logger = logger;
            _stopwatch = new Stopwatch();
            _configuration = configuration;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var isRecordEnabled = _configuration.GetSection("AppSettings").GetValue<bool>("MiddlewareRecordAccessLogsEnabled", false);
            if (isRecordEnabled)
            {
                var api = context.Request.Path.ToString().TrimEnd('/').ToLower();
                var ignoreApis = _configuration.GetSection("AppSettings").GetValue<string>("MiddlewareRecordAccessLogsIgnoreApis");// ConfigHelper.GetContent("AppConfig", "MiddlewareRecordAccessLogsIgnoreApis");

                // 过滤，只有接口
                if (api.Contains("api") && !ignoreApis.Contains(api))
                {
                    _stopwatch.Restart();
                    HttpRequest request = context.Request;

                    var reqData = "";
                    // 获取请求body内容
                    if (request.Method.ToLower().Equals("post") || request.Method.ToLower().Equals("put"))
                    {
                        // 启用倒带功能，就可以让 Request.Body 可以再次读取
                        request.EnableBuffering();

                        Stream stream = request.Body;
                        byte[] buffer = new byte[request.ContentLength.Value];
                        stream.Read(buffer, 0, buffer.Length);
                        reqData = Encoding.UTF8.GetString(buffer);

                        request.Body.Position = 0;
                    }
                    else if (request.Method.ToLower().Equals("get") || request.Method.ToLower().Equals("delete"))
                    {
                        reqData = HttpUtility.UrlDecode(request.QueryString.ToString(), Encoding.UTF8);
                    }

                    // 获取Response.Body内容
                    var originalBodyStream = context.Response.Body;
                    using (var responseBody = new MemoryStream())
                    {
                        context.Response.Body = responseBody;

                        await _next(context);

                        var responseBodyData = await GetResponse(context.Response);

                        await responseBody.CopyToAsync(originalBodyStream);
                    }


                    var dt = DateTime.Now;

                    // 响应完成记录时间和存入日志
                    context.Response.OnCompleted(() =>
                    {
                        _stopwatch.Stop();
                        var userAccessModel = new
                        {
                            API = api,
                            User = _user.Name,
                            IP = context.Connection.RemoteIpAddress?.ToString(),
                            BeginTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                            RequestMethod = request.Method,
                            Agent = request.Headers["User-Agent"].ToString(),
                            OPTime = _stopwatch.ElapsedMilliseconds + "ms",
                            reqData = reqData,
                        };

                        // 自定义log输出
                        var requestInfo = userAccessModel.SerializeJson();
                        Parallel.For(0, 1, e =>
                        {
                            Serilog.Log.Error($"-------------------------\r\nRecordAccessLogs\r\n Data:{DateTime.Now.ToString()}\r\nContent:{requestInfo}");
                        });

                        return Task.CompletedTask;
                    });

                }
                else
                {
                    await _next(context);
                }
            }
            else
            {
                await _next(context);
            }
        }


        /// <summary>
        /// 获取响应内容
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public async Task<string> GetResponse(HttpResponse response)
        {
            response.Body.Seek(0, SeekOrigin.Begin);
            var text = await new StreamReader(response.Body).ReadToEndAsync();
            response.Body.Seek(0, SeekOrigin.Begin);
            return text;
        }
    }
}
